package com.jd.wego.controller;

import com.alibaba.fastjson.JSON;
import com.jd.wego.entity.Article;
import com.jd.wego.entity.Category;
import com.jd.wego.entity.User;
import com.jd.wego.service.CategoryService;
import com.jd.wego.utils.CodeMsg;
import com.jd.wego.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    LoginController loginController;
    @Autowired
    CategoryService categoryService;
    private static final Logger log = LoggerFactory.getLogger(ArticleController.class);

    @PostMapping("/save")
    @ResponseBody
    public Result<Boolean> insertArticle(HttpServletRequest request, @RequestBody Map<String, String> map) {
        User user = loginController.getUserInfo(request);
        if (user == null) {
            log.info("用户未登录");
            return Result.error(CodeMsg.NOT_LOGIN);
        }

        // 需要通过闯过来的categoryName来查找出categoryId
        String name = map.get("name");
        List<Category> categoryList = categoryService.selectCategoryByName(name);
        if (categoryList != null && !categoryList.isEmpty()) {
            return Result.error(CodeMsg.CATEGORY_EXIST);
        }

        Category category = new Category();
        category.setCategoryName(name);
        categoryService.insertCategory(category);
        return Result.success(true);
    }
}
